package com.aitaoxue.palx.ui;

import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationFragment;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.RongIMClient.ErrorCode;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Conversation.ConversationType;

import java.util.Locale;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;

import com.aitaoxue.palx.AppContext;
import com.aitaoxue.palx.R;
import com.aitaoxue.palx.bean.UserInfos;
import com.aitaoxue.palx.db.RongyunContext;
import com.aitaoxue.palx.ui.dialog.DialogHelper;
import com.aitaoxue.palx.ui.dialog.WaitDialog;

/**
 * 
 * 通过intent获得发送过来的数据 1.程序切到后台,点击通知栏进入程序 2.收到push消息
 * 
 */
public class ConversationActivity extends ActionBarActivity implements Callback {

	private static final String TAG = ConversationActivity.class
			.getSimpleName();

	ConversationType mConversationType = null;

	private Handler mHandler;

	private String targetId;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);

		mHandler = new Handler(this);

		setContentView(R.layout.conversation);

		mConversationType = ConversationType.valueOf(getIntent().getData()
				.getLastPathSegment().toUpperCase(Locale.getDefault()));

		initView();

		initData();

		// Intent intent = getIntent();
		//
		// targetId = intent.getData().getQueryParameter("targetId");
		//
		// ConversationType mConversationType = ConversationType.valueOf(intent
		// .getData().getLastPathSegment()
		// .toUpperCase(Locale.getDefault()));
		//
		// enterFragment(mConversationType, targetId);
	}

	// private void enterFragment(ConversationType mConversationType,
	// String targetId) {
	// ConversationFragment fragment = (ConversationFragment)
	// getSupportFragmentManager()
	// .findFragmentById(R.id.conversation);
	//
	// Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName)
	// .buildUpon().appendPath("conversation")
	// .appendPath(mConversationType.getName().toLowerCase())
	// .appendQueryParameter("targetId", targetId).build();
	//
	// fragment.setUri(uri);
	// }

	private void initView() {
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setHomeAsUpIndicator(
				R.drawable.actionbar_back_icon_normal);
		getSupportActionBar().setDisplayShowHomeEnabled(false);

		Intent intent = getIntent();
		
		targetId = intent.getData().getQueryParameter("targetId");

		// Uri uri=intent.getData();

		// push或通知过来
		if (intent.getData().getQueryParameter("push") != null
				&& intent.getData().getQueryParameter("push").equals("true")) {
			// enterActivity(intent);
			String token = AppContext.getInstance().getProperty("user.token");
			reconnect(token);
		} else {
			enterFragment(intent);
		}
	}

	private void reconnect(String token) {
		final WaitDialog dialog = DialogHelper.getWaitDialog(this, "连接中...");
		dialog.show();

		// RongIM.getInstance();

		RongIM.connect(token, new RongIMClient.ConnectCallback() {

			@Override
			public void onSuccess(String arg0) {
				System.out.println("here");
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						dialog.dismiss();
						Intent intent = getIntent();
						if (intent != null) {
							enterFragment(intent);
						}
					}
				});

			}

			@Override
			public void onError(ErrorCode arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onTokenIncorrect() {
				// TODO Auto-generated method stub

			}
		});

	}

	private void enterFragment(Intent intent) {
		if (intent != null) {
			Fragment fragment = null;

			if (intent.getData() != null) {
				if (intent.getData().getPathSegments().get(0)
						.equals("conversation")) {
					fragment = (ConversationFragment) getSupportFragmentManager()
							.findFragmentById(R.id.conversation);
				}
			}

			Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName)
					.buildUpon().appendPath("conversation")
					.appendPath(mConversationType.getName().toLowerCase())
					.appendQueryParameter("targetId", targetId).build();

			((ConversationFragment) fragment).setUri(uri);
		}
	}

	@Override
	public void onBackPressed() {
		startActivity(new Intent(this, MainActivity.class));
		finish();
	}

	@Override
	public boolean handleMessage(Message msg) {
		return false;
	}

	private void initData() {
		if (mConversationType != null) {
			if (mConversationType.equals(Conversation.ConversationType.PRIVATE)) {
				if (RongyunContext.getInstance() != null) {
					UserInfos userInfos = RongyunContext.getInstance()
							.getUserInfoById(targetId);
					if (userInfos == null) {
						getSupportActionBar()
								.setTitle(
										"爱淘学"
												+ targetId.substring(targetId
														.length() - 4));
					} else {
						getSupportActionBar().setTitle(userInfos.getUsername());
					}
				}
			} else if (mConversationType
					.equals(Conversation.ConversationType.SYSTEM)) {
				getSupportActionBar().setTitle("小淘");
			}
		}
	}
}
